package com.daqian.chance.example.admin.modules.system.controller;

import com.daqian.chance.core.rest.RestResult;
import com.daqian.chance.example.admin.modules.system.po.dto.UserLoginDTO;
import com.daqian.chance.example.admin.modules.system.service.ISysUserService;
import com.daqian.chance.redis.conf.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author scott
 * @since 2018-12-17
 */
@Api(tags = "用户登录")
@RestController
@RequestMapping("/sys")
@Slf4j
public class LoginController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisService redisService;

    /**
     * 登录
     * @param userLoginDTO
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public RestResult<?> login(@RequestBody UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            return RestResult.fail("未知账户");
        } catch (IncorrectCredentialsException ice) {
            return RestResult.fail("密码不正确");
        } catch (LockedAccountException lae) {
            return RestResult.fail("账户已锁定");
        } catch (ExcessiveAttemptsException eae) {
            return RestResult.fail("用户名或密码错误次数过多");
        } catch (AuthenticationException ae) {
            return RestResult.fail("用户名或密码不正确");
        }
        if (!subject.isAuthenticated()) {
            token.clear();
            return RestResult.fail("登录失败");
        }
        // 登录成功
        return RestResult.ok();

    }

    /**
     * 退出登录
     * @return
     */
    @ApiOperation("退出登录")
    @PostMapping(value = "/logout")
    public RestResult<?> logout() {
        //用户退出逻辑
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        subject.logout();
        log.info(" 用户【{}】退出登录成功", username);

//        String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
//        //清空用户Token缓存
//        redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
//        //清空用户权限缓存：权限Perms和角色集合
//        redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_ROLE + sysUser.getUsername());
//        redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_PERMISSION + sysUser.getUsername());
        return RestResult.ok("退出登录成功");
    }

//    /**
//     * 用户信息
//     *
//     * @param sysUser
//     * @param RestResult
//     * @return
//     */
//    private RestResult<JSONObject> loginUserInfo(SysUser sysUser, RestResult<JSONObject> RestResult) {
//        String syspassword = sysUser.getPassword();
//        String username = sysUser.getUsername();
//        // 生成token
//        String token = JwtTokenUtil.generateToken(username);
//        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
//        // 设置超时时间
//        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//
//        // 获取用户部门信息
//        JSONObject obj = new JSONObject();
//        List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
//        obj.put("departs", departs);
//        if (departs == null || departs.size() == 0) {
//            obj.put("multi_depart", 0);
//        } else if (departs.size() == 1) {
//            sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
//            obj.put("multi_depart", 1);
//        } else {
//            obj.put("multi_depart", 2);
//        }
//        obj.put("token", token);
//        obj.put("userInfo", sysUser);
//        RestResult.ok(obj);
//        RestResult.success("登录成功");
//        return RestResult;
//    }

}